package com.zsz.crm.workbench.web.controller;

import com.zsz.crm.settings.domain.User;
import com.zsz.crm.settings.service.UserService;
import com.zsz.crm.settings.service.impl.UserServiceImpl;
import com.zsz.crm.utils.*;
import com.zsz.crm.vo.PaginationVO;
import com.zsz.crm.workbench.domain.Activity;
import com.zsz.crm.workbench.domain.ActivityRemark;
import com.zsz.crm.workbench.service.ActivityService;
import com.zsz.crm.workbench.service.impl.ActivityServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ActivityController extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("进入到市场活动控制器");

        //拿到的是url-pattern
        String path=request.getServletPath();

        if ("/workbench/activity/getUserList.do".equals(path)){

            getUserList(response,request);
        }else if ("/workbench/activity/save.do".equals(path)){
            save(response,request);
        }else if ("/workbench/activity/pageList.do".equals(path)){
            pageList(response,request);
        }else if ("/workbench/activity/delete.do".equals(path)){
            delete(response,request);
        }else if ("/workbench/activity/getUserListAndActivity.do".equals(path)){
            getUserListAndActivity(response,request);
        }else if ("/workbench/activity/update.do".equals(path)){
            update(response,request);
        }else if ("/workbench/activity/detail.do".equals(path)){
            detail(response,request);
        }else if ("/workbench/activity/getRemarkListByAid.do".equals(path)){
            getRemarkListByAid(response,request);
        }else if ("/workbench/activity/deleteRemark.do".equals(path)){
            deleteRemark(response,request);
        }else if ("/workbench/activity/saveRemark.do".equals(path)){
            saveRemark(response,request);
        }else if ("/workbench/activity/updateRemark.do".equals(path)){
            updateRemark(response,request);
        }
    }

    private void updateRemark(HttpServletResponse response, HttpServletRequest request) {

        System.out.println("执行修改备注的操作。");

        String id=request.getParameter("id");
        String noteContent=request.getParameter("noteContent");
        String editTime = DateTimeUtil.getSysTime();
        String editBy = ((User)request.getSession().getAttribute("user")).getName();
        // 0表示没修改过，1表示修改过
        String editFlag="1";

        ActivityRemark ar=new ActivityRemark();
        ar.setId(id);
        ar.setNoteContent(noteContent);
        ar.setEditTime(editTime);
        ar.setEditBy(editBy);
        ar.setEditFlag(editFlag);

        ActivityService as= (ActivityService) ServiceFactory.getService(new ActivityServiceImpl());

        boolean flag=as.updateRemark(ar);

        Map<String,Object> map=new HashMap<String, Object>();
        map.put("success",flag);
        map.put("ar",ar);

        PrintJson.printJsonObj(response,map);




    }

    private void saveRemark(HttpServletResponse response, HttpServletRequest request) {
        System.out.println("执行添加备注的操作");

        String noteContent=request.getParameter("noteContent");
        String activityId=request.getParameter("activityId");
        String id=request.getParameter("id");
        String createTime = DateTimeUtil.getSysTime();
        String createBy = ((User)request.getSession().getAttribute("user")).getName();
        String editFlag="0";

        ActivityRemark ar=new ActivityRemark();
        ar.setNoteContent(noteContent);
        ar.setActivityId(activityId);
        ar.setId(id);
        ar.setCreateTime(createTime);
        ar.setCreateBy(createBy);
        ar.setEditFlag(editFlag);

        ActivityService as= (ActivityService) ServiceFactory.getService(new ActivityServiceImpl());

        boolean flag=as.saveRemark(ar);

        //向前端返回两项信息，使用map或者vo都行

        Map<String,Object> map=new HashMap<String, Object>();
        map.put("success",flag);
        map.put("ar",ar);

        PrintJson.printJsonObj(response,map);







    }

    private void deleteRemark(HttpServletResponse response, HttpServletRequest request) {

        System.out.println("删除备注操作");

        String id = request.getParameter("id");

        ActivityService as= (ActivityService) ServiceFactory.getService(new ActivityServiceImpl());

        boolean flag = as.deleteRemark(id);
        PrintJson.printJsonFlag(response,flag);

    }

    private void getRemarkListByAid(HttpServletResponse response, HttpServletRequest request) {

        System.out.println("根据市场活动id，取得备注信息列表");

        String activityId = request.getParameter("activityId");

        ActivityService as= (ActivityService) ServiceFactory.getService(new ActivityServiceImpl());

        List<ActivityRemark> arList = as.getRemarkListByAid(activityId);

        PrintJson.printJsonObj(response,arList);
    }

    private void detail(HttpServletResponse response, HttpServletRequest request) throws ServletException, IOException {

        System.out.println("进入到跳转到详细信息页的操作");

        String id=request.getParameter("id");

        ActivityService as= (ActivityService) ServiceFactory.getService(new ActivityServiceImpl());

        Activity a=as.detail(id);

        //能用小的作用域就不用大的作用域
        request.setAttribute("a",a);
        request.getRequestDispatcher("/workbench/activity//detail.jsp").forward(request,response);

    }

    private void update(HttpServletResponse response, HttpServletRequest request) {
        System.out.println("执行市场活动修改操作");

        String  id= request.getParameter("id");
        String  owner=request.getParameter("owner");
        String  name=request.getParameter("name");
        String  startDate=request.getParameter("startDate");
        String  endDate=request.getParameter("startDate");
        String  cost=request.getParameter("cost");
        String  description=request.getParameter("description");
        //修改时间：当前系统时间
        String  editTime= DateTimeUtil.getSysTime();
        //修改人：当前登录用户
        String  editBy= ((User) request.getSession().getAttribute("user")).getName();

        Activity activity=new Activity();
        activity.setId(id);
        activity.setOwner(owner);
        activity.setName(name);
        activity.setStartDate(startDate);
        activity.setEndDate(endDate);
        activity.setCost(cost);
        activity.setDescription(description);
        activity.setEditTime(editTime);
        activity.setEditBy(editBy);


        ActivityService as= (ActivityService) ServiceFactory.getService(new ActivityServiceImpl());

        boolean flag=as.update(activity);
        PrintJson.printJsonFlag(response,flag);


    }

    private void getUserListAndActivity(HttpServletResponse response, HttpServletRequest request) {

        System.out.println("进入到查询用户信息列表和根据市场活动id查询单条记录的操作");

        String id=request.getParameter("id");

        ActivityService as = (ActivityService) ServiceFactory.getService(new ActivityServiceImpl());


        /*

         总结：
             controller调用service的方法，返回值应该是什么，
             你得想一想前端要什么，就要从service层取什么

          前端需要的信息，管业务层去要
          uList
          a

          以上两项信息，复用率不高，我们选择使用map打包这两项信息即可（返回信息可以用vo也可以用map）
          map




          把自己当成controller看看需要向service层要什么？那controller需要什么呢？
          取决于前端需要什么数据：（这里前端需要  uList和a   用map返回数据就行了）



         */
        Map<String,Object> map= as.getUserListAndActivity(id);
        PrintJson.printJsonObj(response,map);


    }

    private void delete(HttpServletResponse response, HttpServletRequest request) {
        System.out.println("执行市场活动的删除操作");

        String ids[]=request.getParameterValues("id");

        ActivityService as= (ActivityService) ServiceFactory.getService(new ActivityServiceImpl());

        boolean flag=as.delete(ids);

        PrintJson.printJsonFlag(response,flag);


    }

    private void pageList(HttpServletResponse response, HttpServletRequest request) {
        System.out.println("进入到查询市场活动信息列表的操作（结合条件查询+分页查询）");

        String name=request.getParameter("name");
        String owner=request.getParameter("owner");
        String startDate=request.getParameter("startDate");
        String endDate=request.getParameter("endDate");
        String pageNoStr=request.getParameter("pageNo");
        int pageNo=Integer.valueOf(pageNoStr);
        //每页展现的记录数
        String pageSizeStr=request.getParameter("pageSize");
        int pageSize=Integer.valueOf(pageSizeStr);
        //计算出略过的记录数
        int skipCount=(pageNo-1)*pageSize;

        Map<String,Object> map=new HashMap<String, Object>();
        map.put("name",name);
        map.put("owner",owner);
        map.put("startDate",startDate);
        map.put("endDate",endDate);
        map.put("skipCount",skipCount);
        map.put("pageSize",pageSize);

        ActivityService as= (ActivityService) ServiceFactory.getService(new ActivityServiceImpl());

        /*
           controller要求service返回什么呢？在于前端向控制器要什么。
           前端要：市场活动信息列表
                  查询的总条数

                  业务层拿到了以上两项信息之后，如何做返回呢？
                  map
                  map.put("dataList":dataList)
                  map.put("total",total)
                  PrintJSON map-->json
                  {"total":100,"dataList":[{市场活动1},{2},{3}]}


                  vo(要让vo达到通用性，这样才能达到我们创建vo的目的)

                  PaginationVO<T>
                        private int total;
                        // private List<Activity> dataList;(不行这样就写死了)

                        //应该这样写
                        private List<T> dataList;

                        PaginationVO<Activity> vo = new PaginationVO<>;
                        vo.setTotal(total);
                        vo.setDataList(dataList);
                        PrintJSON vo ---> json
                         {"total":100,"dataList":[{市场活动1},{2},{3}]}


                        将来分页查询，每个模块都有，所以我们选择使用一个通用vo，操作起来比较方便



         */

        PaginationVO<Activity> vo= as.pageList(map);

        //vo--->{"total":100,"dataList":[{市场活动1},{2},{3}]}
        PrintJson.printJsonObj(response,vo);

    }

    private void save(HttpServletResponse response, HttpServletRequest request) {

        System.out.println("执行市场活动的添加操作");
        String  id= UUIDUtil.getUUID();
        String  owner=request.getParameter("owner");
        String  name=request.getParameter("name");
        String  startDate=request.getParameter("startDate");
        String  endDate=request.getParameter("startDate");
        String  cost=request.getParameter("cost");
        String  description=request.getParameter("description");
        //创建时间：当前系统时间
        String  createTime= DateTimeUtil.getSysTime();
        //创建人：当前登录用户
        String  createBy= ((User) request.getSession().getAttribute("user")).getName();

        Activity activity=new Activity();
        activity.setId(id);
        activity.setOwner(owner);
        activity.setName(name);
        activity.setStartDate(startDate);
        activity.setEndDate(endDate);
        activity.setCost(cost);
        activity.setDescription(description);
        activity.setCreateTime(createTime);
        activity.setCreateBy(createBy);


        ActivityService as= (ActivityService) ServiceFactory.getService(new ActivityServiceImpl());

        boolean flag=as.save(activity);
        PrintJson.printJsonFlag(response,flag);


    }

    private void getUserList(HttpServletResponse response, HttpServletRequest request) {
        System.out.println("取得用户列表");

        UserService us= (UserService) ServiceFactory.getService(new UserServiceImpl());

        List<User> uList=us.getUserList();

        PrintJson.printJsonObj(response,uList);

    }


}

